<template>
  <div class="chat-container">
    <!-- 对话消息列表 -->
    <div class="chat-messages" ref="messageList">
      <div v-for="(message, index) in conversation" :key="index" :class="['message', message.role]">
        <p>{{ message.content }}</p>
      </div>
    </div>
    <!-- 输入框、语音输入按钮、发送按钮和暂停按钮 -->
    <div class="chat-input">
      <textarea v-model="userInput" placeholder="输入你的消息..." @keyup.enter="sendMessage"></textarea>
      <button @click="toggleSpeechRecognition" :class="{ 'listening': isListening }">
        {{ isListening ? '停止录音' : '语音输入' }}
      </button>
      <button @click="sendMessage">发送</button>
      <button @click="pauseInteraction">暂停</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';

// 对话消息列表
const conversation = ref<{ role: 'user' | 'assistant'; content: string }[]>([]);
// 用户输入内容
const userInput = ref('');
// 消息列表 DOM 引用
const messageList = ref<HTMLElement | null>(null);
// 语音合成实例
const synth = ref<SpeechSynthesis | null>(window.speechSynthesis);
// 当前语音合成的语音实例
const currentUtterance = ref<SpeechSynthesisUtterance | null>(null);
// 语音识别实例
// 在文件顶部添加类型声明

// 添加 SpeechRecognition 接口声明
interface SpeechRecognition extends EventTarget {
  lang: string;
  interimResults: boolean;
  start(): void;
  stop(): void;
  onresult: (event: SpeechRecognitionEvent) => void;
  onend: () => void;
  onerror: (event: SpeechRecognitionErrorEvent) => void;
}

// 添加 SpeechRecognitionEvent 接口声明
interface SpeechRecognitionEvent extends Event {
  results: SpeechRecognitionResultList;
}

// 添加 SpeechRecognitionErrorEvent 接口声明
interface SpeechRecognitionErrorEvent extends Event {
  error: string;
}

// 然后修改代码中的类型引用
const recognition = ref<SpeechRecognition | null>(null);
// 添加这两个变量的声明
const isListening = ref(false);
const isProcessingSpeech = ref(false);

// 修改初始化函数
const initSpeechRecognition = async () => {
  try {
    if ('webkitSpeechRecognition' in window) {
      recognition.value = new (window as any).webkitSpeechRecognition() as SpeechRecognition;
    } else if ('SpeechRecognition' in window) {
      recognition.value = new (window as any).SpeechRecognition() as SpeechRecognition;
    } else {
      alert('您的浏览器不支持语音识别功能');
      return;
    }

    recognition.value.lang = 'zh-CN';
    recognition.value.interimResults = false;

    recognition.value.onresult = (event: SpeechRecognitionEvent) => {
      if (isProcessingSpeech.value) return;
      isProcessingSpeech.value = true;
      const transcript = event.results[0][0].transcript;
      userInput.value = transcript;
      sendMessage().finally(() => {
        isProcessingSpeech.value = false;
      });
    };

    recognition.value.onend = () => {
      isListening.value = false;
    };

    recognition.value.onerror = (event: SpeechRecognitionErrorEvent) => {
      console.error('语音识别错误:', event.error);
      const errorMessages: Record<string, string> = {
        'not-allowed': '请授予麦克风权限',
        'no-speech': '未检测到语音，请重试',
        'audio-capture': '无法访问麦克风'
      };
      alert(errorMessages[event.error] || `语音识别错误: ${event.error}`);
      isListening.value = false;
    };
  } catch (error) {
    console.error('初始化语音识别失败:', error);
    alert('初始化语音识别失败，请刷新页面重试');
  }
};

// 切换语音识别状态
const toggleSpeechRecognition = async () => {
  if (isProcessingSpeech.value) {
    alert('正在处理上一次语音输入，请稍候...');
    return;
  }
  if (!recognition.value) {
    await initSpeechRecognition();
  }

  if (isListening.value) {
    recognition.value?.stop();
  } else {
    try {
      recognition.value?.start();
      isListening.value = true;
    } catch (error) {
      console.error('启动语音识别失败:', error);
      alert('启动语音识别失败，请检查麦克风权限');
      isListening.value = false;
    }
  }
};

// 暂停交互函数
const pauseInteraction = () => {
  // 停止语音识别
  if (recognition.value && isListening.value) {
    recognition.value.stop();
    isListening.value = false;
  }
  // 停止语音合成
  if (synth.value && synth.value.speaking) {
    synth.value.cancel();
    currentUtterance.value = null;
  }

  // 添加 AI 回复
  // 修改这一行
  const pauseMessage = { role: 'system' as 'assistant', content: '对话已暂停。' };
  
  // 以及这一行
  const errorMessage = { role: 'system' as 'assistant', content: '抱歉，服务暂时不可用，请稍后再试。' };
  conversation.value.push(pauseMessage);

  // 朗读 AI 回复
  speakText(pauseMessage.content);

  // 滚动到最新消息
  scrollToBottom();
};

// 发送消息函数
const sendMessage = async () => {
  if (!userInput.value.trim()) return;

  // 添加用户消息到对话列表
  const userMessage = { role: 'user', content: userInput.value };
  conversation.value.push({ role: 'user' as const, content: userInput.value });
  userInput.value = '';

  try {
    // 调用 AI 接口获取回复
    const response = await axios.post(
      'https://api.deepseek.com/chat/completions',
      {
        model: 'deepseek-chat',
        messages: conversation.value
      },
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer sk-329970a063324a14abdd8f8cfc299188`
        }
      }
    );

    // 添加 AI 回复到对话列表
    const aiMessage = { role: 'assistant', content: response.data.choices[0].message.content };
    conversation.value.push({ role: 'assistant' as const, content: aiMessage.content });

    // 朗读 AI 回复
    speakText(aiMessage.content);
  } catch (error) {
    console.error('获取 AI 回复失败:', error);
    // 添加错误提示到对话列表
    const errorMessage = { role: 'system' as 'assistant', content: '抱歉，服务暂时不可用，请稍后再试。' };
    conversation.value.push(errorMessage);
    // 朗读错误提示
    speakText(errorMessage.content);
  }

  // 滚动到最新消息
  scrollToBottom();
};

// 语音合成函数
const speakText = (text: string) => {
  if (synth.value && synth.value.speaking) {
    synth.value.cancel();
  }

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = 'zh-CN';
  utterance.volume = 1; // 音量，范围 0 - 1
  utterance.rate = 1; // 语速，范围 0.1 - 10
  utterance.pitch = 1; // 音调，范围 0 - 2

  currentUtterance.value = utterance;
  synth.value?.speak(utterance);
};

// 滚动到消息列表底部
const scrollToBottom = () => {
  if (messageList.value) {
    messageList.value.scrollTop = messageList.value.scrollHeight;
  }
};

onMounted(() => {
  scrollToBottom();
  // 检查浏览器是否支持语音合成
  if (!('speechSynthesis' in window)) {
    alert('您的浏览器不支持语音合成功能');
  }
  // 初始化语音识别
  initSpeechRecognition();
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
}

.user {
  background-color: #e3f2fd;
  margin-left: 20%;
}

.assistant {
  background-color: #f1f8e9;
  margin-right: 20%;
}

.chat-input {
  display: flex;
  align-items: center;
}

.chat-input textarea {
  flex: 1;
  padding: 10px;
  margin-right: 10px;
}

.chat-input button {
  padding: 10px 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  cursor: pointer;
  margin-right: 10px;
}

.chat-input button:hover {
  background-color: #45a049;
}

.chat-input button.listening {
  background-color: #ff4444;
}
</style>
